package com.beta.cust.bind.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.beta.cat.service.RedissonService;
import com.beta.cust.bind.api.model.CrmCustDetailEntity;
import com.beta.cust.bind.api.request.CustAuthReq;
import com.beta.cust.bind.api.request.CustDetailReq;
import com.beta.cust.bind.api.request.CustListReq;
import com.beta.cust.bind.api.response.CustDetailResp;
import com.beta.cust.bind.api.response.CustListResp;
import com.beta.cust.bind.api.service.IRpcCustService;
import com.beta.cust.bind.builder.CustBuilder;
import com.beta.cust.bind.config.CfgSelfRefreshBean;
import com.beta.cust.bind.config.ResultCode;
import com.beta.cust.bind.constant.BusinessConstant;
import com.beta.cust.bind.constant.RedisConstant;
import com.beta.cust.bind.mapper.entity.CrmCustDetail;
import com.beta.cust.bind.mapper.entity.EmpCustRef;
import com.beta.cust.bind.mapper.entity.EmployeeInfo;
import com.beta.cust.bind.service.*;
import com.beta.cust.bind.service.impl.CustInfoServiceImpl;
import com.beta.cust.bind.vo.CrmCustDetailVO;
import com.beta.elephant.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.Duration;


/**
 * @Auther: pcc
 * @Date: 2024/3/28 15:27
 * @Description:
 */
@Slf4j
@DubboService
public class RpcCustServiceImpl implements IRpcCustService {

    @Resource
    private CustInfoServiceImpl custInfoService;

    @Autowired
    private IEmployeeInfoService employeeInfoService;

    @Autowired
    private IEmpCustRefService empCustRefService;

    @Autowired
    private ICrmCustDetailService crmCustDetailService;

    @Autowired
    private ICrmInterfaceService crmInterfaceService;

    @Autowired
    private RedissonService redissonService;

    @Autowired
    private CfgSelfRefreshBean cfgSelfRefreshBean;

    @Override
    public ResultVO<CustDetailResp> custDetail(CustDetailReq req) {
        CustDetailResp custInfo = custInfoService.selectByUserAndExternalId(req.getUserId(), req.getContactUserId(), req.getCorpId());
        if (null == custInfo) {
            return ResultVO.failure(ResultCode.ERROR_CODE_1101);
        }
        //查询理财经理的头像
        EmployeeInfo employeeInfo = employeeInfoService.getBaseMapper().selectOne(new LambdaQueryWrapper<EmployeeInfo>()
                .eq(EmployeeInfo::getDelFlag, BusinessConstant.IS_NOT_DEL_FLAG)
                .eq(EmployeeInfo::getUserId, req.getUserId())
                .eq(EmployeeInfo::getCorpId, req.getCorpId()));
        custInfo.setCustManagerAvatar(null != employeeInfo ? employeeInfo.getAvatar() : StringUtils.EMPTY);
        //非管护关系不展示手机号
        if(BusinessConstant.NOT_CERTIFICATED.equals(custInfo.getIsBelong())){
            custInfo.setPhone(StringUtils.EMPTY);
        }
        return ResultVO.success(custInfo);
    }

    @Override
    public ResultVO<CustListResp> custList(CustListReq req) {
        CustListResp resp = new CustListResp();
        IPage<CustDetailResp> resultPage = custInfoService.selectPage(req);
        resp.setLists(resultPage.getRecords());
        if(!CollectionUtils.isEmpty(resp.getLists())){
            resp.getLists().stream().forEach(entity->{
                //非管护关系不展示手机号
               if(BusinessConstant.NOT_CERTIFICATED.equals(entity.getIsBelong())){
                    entity.setPhone(StringUtils.EMPTY);
               }
            });
        }
        resp.setPageNo((int) resultPage.getCurrent());
        resp.setTotal((int) resultPage.getTotal());
        return ResultVO.success(resp);
    }

    @Override
    public ResultVO<Boolean> custAuth(CustAuthReq req) {
        String lockKey = String.format(RedisConstant.AUTH_LOCK_KEY,req.getUserId(),req.getContactUserId());
        try {
            if (!redissonService.tryLock(lockKey, RedisConstant.RELEASE_TIME, RedisConstant.WAIT_TIME)) {
                return ResultVO.failure(ResultCode.ERROR_CODE_2106);
            }
            if (StringUtils.isEmpty(req.getCustManagePhone())) {
                req.setCustManagePhone(getLatestPhone(req.getUserId(), req.getCorpId()));
            }
            if (StringUtils.isEmpty(req.getCustManagePhone())) {
                return ResultVO.failure(ResultCode.ERROR_CODE_2105);
            }
            //1、调用校验手机验证码合法性
//            String key = String.format(RedisConstant.PHONE_VERIFICATION_CODE, req.getCustManagePhone());
//            String code = redissonService.getStr(key);
//            if (StringUtils.isEmpty(code) || !code.equals(req.getCode())) {
//                return ResultVO.failure(ResultCode.ERROR_CODE_2101);
//            }
            //2、查询企微用户-客户关系表
            EmpCustRef custRef = empCustRefService.selectEmpCustRef(req.getUserId(), req.getContactUserId(), req.getCorpId());
            if (null == custRef) {
                return ResultVO.failure(ResultCode.ERROR_CODE_2103);
            }
            //3、调用行方认证接口
            CrmCustDetailVO result = crmInterfaceService.queryDetail(req.getCustPhone(), req.getCustManagePhone());
            if (null == result) {
                return ResultVO.failure(ResultCode.ERROR_CODE_2102.getCode(),
                        StringUtils.isNotEmpty(cfgSelfRefreshBean.getCrmCustNullTips()) ? cfgSelfRefreshBean.getCrmCustNullTips() : ResultCode.ERROR_CODE_2102.getMsg());
            }
            //4、保存认证结果到本地
            CrmCustDetail crmCustDetail = CustBuilder.buildCustDetail(result);
            custRef.setCertified(BusinessConstant.IS_CERTIFICATED);
            crmCustDetailService.dealCustRel(crmCustDetail, custRef);
        }finally {
            redissonService.unlock(lockKey);
        }
        return ResultVO.success(true);
    }

    @Override
    public ResultVO<String> latestAuthPhone(CustDetailReq req) {
        CustDetailResp custInfo = custInfoService.getLatest(req.getUserId(), req.getCorpId());
        if (null != custInfo && StringUtils.isNotEmpty(custInfo.getCustManagerPhone())) {
            String key = String.format(RedisConstant.LATEST_AUTH_PHONE, req.getCorpId(), req.getUserId());
            redissonService.setStr(key, custInfo.getCustManagerPhone());
            redissonService.expire(key, Duration.ofMinutes(5));
        }
        return ResultVO.success(null != custInfo ? custInfo.getCustManagerPhone() : StringUtils.EMPTY);
    }

    @Override
    public ResultVO<CrmCustDetailEntity> queryCrmCustDetail(String custPhone, String managerPhone) {
        //1、调用行方认证接口
        CrmCustDetailVO result = crmInterfaceService.queryDetail(custPhone, managerPhone);
        if (null == result) {
            return ResultVO.failure(ResultCode.ERROR_CODE_2102);
        }
        return ResultVO.success(CustBuilder.buildCustDetailEntity(result));
    }

    /**
     * 获取最近一次认证的理财经理手机号
     *
     * @param userId
     * @return
     */
    @Override
    public String getLatestPhone(String userId, String corpId) {
        String key = String.format(RedisConstant.LATEST_AUTH_PHONE, corpId, userId);
        String phone = redissonService.getStr(key);
        if (StringUtils.isNotEmpty(phone)) {
            return phone;
        }
        CustDetailReq req = new CustDetailReq();
        req.setUserId(userId);
        req.setCorpId(corpId);
        return latestAuthPhone(req).getData();
    }
}
